package cn.lyb.service.impl;

import cn.lyb.entity.User;
import cn.lyb.service.IService;
import cn.lyb.service.NotFoundException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
public class ServiceImpl implements IService {

    static List<User> users = new ArrayList<>(10);

    static {
        for (int i = 0; i < 10; i++) {
            User user = new User();
            user.setId((long) (i + 1));
            user.setUsername("name" + i + 1);
            users.add(user);
        }
    }

    private User filterById(Long id) throws NotFoundException {
        log.info("正在执行[{}]", "filterById");
        List<User> collect = users.stream().filter(user -> user.getId().equals(id)).collect(Collectors.toList());
        if (collect.isEmpty()) {
            throw new NotFoundException("id不存在");
        }
        return collect.get(0);
    }

    @Cacheable(value = "user", key = "#id")
    @Override
    public User getById(Long id) throws NotFoundException {
        return filterById(id);
    }

    @Cacheable(value = "users")
    @Override
    public List<User> getAll() {
        log.info("如果执行这段代码则代表来自数据库");
        return users;
    }

    @CacheEvict(value = {"user", "users"}, key = "#user.id")
    @Caching(evict = {
            @CacheEvict(value = "user", key = "#user.id"),
            @CacheEvict(value = "users", allEntries = true)
    })
    @Override
    public void editById(User user) throws NotFoundException {
        filterById(user.getId()).setUsername(user.getUsername());
    }

    @Caching(evict = {
            @CacheEvict(value = "user", key = "#id"),
            @CacheEvict(value = "users", allEntries = true)
    })
    @Override
    public void remove(Long id) {
        int index = -1;
        for (int i = 0; i < users.size(); i++) {
            if (users.get(i).getId().equals(id)) {
                index = 0;
            }
        }
        if (index > -1) {
            users.remove(index);
        }
    }
}
